﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;

namespace Esb.Domain.Helpers
{
    /// <summary>
    /// rest服务代理
    /// </summary>
    class RestServiceAgent
    {
        public string ProcessCallService(string requestBody, string serviceUrl, string methodName)
        {
            Uri uri = new Uri(serviceUrl + "/" + methodName);
            string result = string.Empty;

            using (HttpClient httpClient = new HttpClient())
            {
                string contentString = requestBody;
                using (StringContent httpContent = new StringContent(contentString, Encoding.UTF8, "application/json"))
                {
                    Task<HttpResponseMessage> postTask = httpClient.PostAsync(uri, httpContent);
                    postTask.Wait();

                    if (!postTask.Result.IsSuccessStatusCode)
                    {
                        throw new Exception(string.Format("ProcessCallService, Status Code:{0}, Reason:{1}.", postTask.Result.StatusCode, postTask.Result.ReasonPhrase));
                    }
                    else
                    {
                        Task<string> readTask = postTask.Result.Content.ReadAsStringAsync();
                        readTask.Wait();
                        result = readTask.Result;
                        return result;
                    }
                }
            }
        }
    }
}
